package com.cloudsigns.factorymanager2.engineering.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudsigns.factorymanager2.R;
import com.cloudsigns.factorymanager2.cusenum.CommonEnum;
import com.cloudsigns.factorymanager2.engineering.IView.IUploadPhotoView;
import com.cloudsigns.factorymanager2.engineering.IView.InAddPublicationOrderView;
import com.cloudsigns.factorymanager2.engineering.IView.InRegionListView;
import com.cloudsigns.factorymanager2.engineering.adapter.AddPublicationOrderAdapter;
import com.cloudsigns.factorymanager2.engineering.adapter.GridAdapter;
import com.cloudsigns.factorymanager2.engineering.adapter.PopWindowAdapter;

import com.cloudsigns.factorymanager2.engineering.bean.DialogItemBean;
import com.cloudsigns.factorymanager2.engineering.bean.MediaBean;
import com.cloudsigns.factorymanager2.engineering.bean.RegionBean;
import com.cloudsigns.factorymanager2.engineering.customview.BottomListDialog;
import com.cloudsigns.factorymanager2.engineering.customview.DateViewDialog;
import com.cloudsigns.factorymanager2.engineering.customview.SpinerPopWindow;
import com.cloudsigns.factorymanager2.engineering.presenter.AddPublicationOrderPresenter;
import com.cloudsigns.factorymanager2.engineering.presenter.RegionListPresenter;
import com.cloudsigns.factorymanager2.engineering.presenter.UploadPhotoPresenter;
import com.cloudsigns.factorymanager2.engineering.utils.PhotoUtil;
import com.cloudsigns.factorymanager2.project.activity.AddEngineeringInstallationOrderActivity;
import com.cloudsigns.factorymanager2.project.myinerface.ItemRemoveListener;
import com.cloudsigns.factorymanager2.project.utils.ConstantUtil;
import com.cloudsigns.factorymanager2.project.utils.DateUtil;
import com.cloudsigns.factorymanager2.project.utils.FileUtil;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * Created by tony on 2018/5/5.
 */

public class AddPublicationOrderActivity extends Activity implements View.OnClickListener, InRegionListView, InAddPublicationOrderView, IUploadPhotoView, ItemRemoveListener, AdapterView.OnItemClickListener, BottomListDialog.OnItemDialogClick {
    private View rl_back;
    private TextView tv_title;
    private ImageView img_add_product;
    private View rl_add_product;
    //    private ListView lv;
    private TextView btn_save;
    private TextView edt_airport_name, edt_ndustry_classification;
    private EditText edt_publication_content;
    private TextView edt_completion_date;
    private ImageView img_completion_date;
    private ScrollView scrollview;
    private LinearLayout ll_region;
    private String TAG = AddPublicationOrderActivity.class.getSimpleName();
    AddPublicationOrderPresenter addPublicationOrderPresenter;
    RegionListPresenter mediaRegionListPresenter;
    private SpinerPopWindow<String> airportPopwindow;
    private PopWindowAdapter airportPopwindowAdapter;
    private SpinerPopWindow<String> classificationPopwindow;
    private PopWindowAdapter classificationtPopwindowAdapter;
    private List<String> classificationStrLs = new ArrayList<String>();
    private int AIRPORT = 1;
    private int INDUSTRY = 2;
    private int currentPop = -1;
    private LayoutInflater layoutInflater;
    private List<String> airPopStrLs = new ArrayList<String>();
    List<RegionBean> airPopRegionBeanLs;
    private RegionBean selectedRegionBean;
    private List<MediaBean> datas = new ArrayList<>();
    private List<String> selectedItemList = new ArrayList<String>();
    Map<String, List<MediaBean>> selectedMeidaBeanMap = new HashMap<>();
    private GridView gridView;
    private GridAdapter gridAdapter;
    private List<String> pathList = new ArrayList<>();
    private List<String> serverUrlList = new ArrayList<>();
    private String filePath;
    private UploadPhotoPresenter uploadPhotoPresenter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    );
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.layout_add_publication_order);

        addPublicationOrderPresenter = new AddPublicationOrderPresenter(this);
        mediaRegionListPresenter = new RegionListPresenter(this);
        uploadPhotoPresenter = new UploadPhotoPresenter(this);
        layoutInflater = getLayoutInflater();
        init();
        mediaRegionListPresenter.getMediaRegionList();


    }

    private void init() {
        rl_back = findViewById(R.id.rl_back);
        tv_title = findViewById(R.id.tv_title);
        rl_add_product = findViewById(R.id.rl_add_product);
//        lv = findViewById(R.id.lv);
        btn_save = findViewById(R.id.btn_save);
        edt_airport_name = findViewById(R.id.edt_airport_name);
        edt_ndustry_classification = findViewById(R.id.edt_ndustry_classification);
        edt_completion_date = findViewById(R.id.edt_completion_date);
        edt_publication_content = findViewById(R.id.edt_publication_content);
        img_completion_date = findViewById(R.id.img_completion_date);
        scrollview = findViewById(R.id.scrollview);
        ll_region = findViewById(R.id.ll_region);

        tv_title.setText("上刊工单");
        rl_back.setOnClickListener(this);
        rl_add_product.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        edt_airport_name.setOnClickListener(this);
        edt_ndustry_classification.setOnClickListener(this);
        edt_completion_date.setOnClickListener(this);
        img_completion_date.setOnClickListener(this);


        airportPopwindow = new SpinerPopWindow<String>(this, this);
        airportPopwindowAdapter = new PopWindowAdapter(this, TAG);
        airportPopwindowAdapter.setData(airPopStrLs);
        airportPopwindow.setAdapter(airportPopwindowAdapter);

        classificationStrLs.add("机场");
        classificationStrLs.add("其他");
        classificationPopwindow = new SpinerPopWindow<String>(this, this);
        classificationtPopwindowAdapter = new PopWindowAdapter(this, TAG);
        classificationtPopwindowAdapter.setData(classificationStrLs);
        classificationPopwindow.setAdapter(classificationtPopwindowAdapter);

        pathList.add("paizhao");
        gridView = findViewById(R.id.gridView);
        gridView.setNumColumns(3);
        gridAdapter = new GridAdapter(this);
        gridAdapter.setData(pathList);
        gridView.setAdapter(gridAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long l) {

                String imgs = (String) parent.getItemAtPosition(position);
                if ("paizhao".equals(imgs)) {
                    showListDialog();
                } else {

                }
            }
        });

    }

    private void initData() {
        if (null != datas) {
            for (MediaBean mediaRegionBean : datas) {
                String areaName = mediaRegionBean.getAreaName();

                if (selectedMeidaBeanMap.containsKey(areaName)) {
                    selectedMeidaBeanMap.get(areaName).add(mediaRegionBean);
                } else {
                    List<MediaBean> beanList = new ArrayList<>();
                    beanList.add(mediaRegionBean);
                    selectedMeidaBeanMap.put(areaName, beanList);

                }
            }
        }

        updateUi();
    }

    private void updateUi() {


        if (null != selectedMeidaBeanMap && null != ll_region) {
            ll_region.removeAllViews();

            for (Map.Entry<String, List<MediaBean>> entry : selectedMeidaBeanMap.entrySet()) {
                View view = layoutInflater.inflate(R.layout.layout_point_location_content, null);
                TextView tv_area_name = view.findViewById(R.id.tv_area_name);
                tv_area_name.setText(entry.getKey());

                ListView lv_media = view.findViewById(R.id.lv_media);

                List<MediaBean> mediaRegionBeanList = entry.getValue();
                AddPublicationOrderAdapter adapter = new AddPublicationOrderAdapter(this, TAG);
//                PointLocationAdapter adapter = new PointLocationAdapter(this, TAG);
                adapter.setData(mediaRegionBeanList);
                adapter.setItemRemoveListener(this);
                lv_media.setAdapter(adapter);
                view.setTag(mediaRegionBeanList);


                ll_region.addView(view);


            }
        }

        scrollview.smoothScrollTo(0, 0);

    }

    private void save() {
        if (null != addPublicationOrderPresenter)
            addPublicationOrderPresenter.addPublicationOrder();
    }


    private void initAirportPopData() {
        if (null != airPopRegionBeanLs) {
            airPopStrLs.clear();
            for (RegionBean regionBean : airPopRegionBeanLs) {
                airPopStrLs.add(regionBean.getRegionName());
            }
            airportPopwindowAdapter.setData(airPopStrLs);
            airportPopwindowAdapter.notifyDataSetChanged();
        }
    }


    private void showListDialog() {
        DialogItemBean[] items = new DialogItemBean[]{
                new DialogItemBean(R.string.camera,
                        R.layout.dialog_list_item_normal),
                new DialogItemBean(R.string.gallary,
                        R.layout.dialog_list_item_normal),
                new DialogItemBean(R.string.cancel,
                        R.layout.dialog_list_item_normal)};
        BottomListDialog dialog = new BottomListDialog(this, Arrays.asList(items));
        dialog.setItemClick(this);
        dialog.show();
    }

    private void showAirportPop() {
        airportPopwindow.setWidth(edt_airport_name.getWidth());
        airportPopwindow.showAsDropDown(edt_airport_name);
    }

    private void showClassificationPop() {
        classificationPopwindow.setWidth(edt_ndustry_classification.getWidth());
        classificationPopwindow.showAsDropDown(edt_ndustry_classification);
    }

    private void showDateDialog() {
        DateViewDialog endDateChooseDialog = new DateViewDialog(this,
                new DateViewDialog.DateChooseInterface() {
                    @Override
                    public void getDateTime(String time, boolean longTimeChecked) {
                        edt_completion_date.setText(time);
                    }
                });
        endDateChooseDialog.setTimePickerGone(true);

        Calendar dateAndTime = Calendar.getInstance(Locale.getDefault());

        endDateChooseDialog.setDateDialogTitle(dateAndTime.get(Calendar.YEAR) + "-" + (dateAndTime.get(Calendar.MONTH) + 1) + "-" + dateAndTime.get(Calendar.DAY_OF_MONTH));
        endDateChooseDialog.showDateChooseDialog();

    }

    @Override
    public void remove(int positon) {

    }

    @Override
    public void remove(View view) {
        MediaBean bean = (MediaBean) view.getTag();
        String areaName = bean.getAreaName();
        if (selectedMeidaBeanMap.containsKey(areaName)) {
            selectedMeidaBeanMap.get(areaName).remove(bean);
            if (selectedMeidaBeanMap.get(areaName).size() == 0)
                selectedMeidaBeanMap.remove(areaName);

            selectedItemList.remove(bean.getId());
            datas.remove(bean);
            updateUi();
        }

    }

    @Override
    public void onItemDialogClick(DialogItemBean item) {

        switch (item.getmTextId()) {
            case R.string.camera: {
                PhotoUtil.startCamear(AddPublicationOrderActivity.this, null);
                break;

            }

            case R.string.gallary: {
                PhotoUtil.startGallery(AddPublicationOrderActivity.this, null);
                break;
            }
            default:
                break;
        }

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (currentPop == AIRPORT) {
            edt_airport_name.setText(airPopStrLs.get(i));
            selectedRegionBean = airPopRegionBeanLs.get(i);
        } else if (currentPop == INDUSTRY) {
            edt_ndustry_classification.setText(classificationStrLs.get(i));
        }


        if (null != airportPopwindow)
            airportPopwindow.dismiss();
        if (null != classificationPopwindow)
            classificationPopwindow.dismiss();
    }

    @Override
    public void onClick(View view) {
        TextView tv;
        Intent mIntent;
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.rl_add_product:
                if (null != selectedRegionBean) {
                    mIntent = new Intent(AddPublicationOrderActivity.this, SelectMeidaForSuperActivity.class);
                    mIntent.putExtra(ConstantUtil.KEY_1, (Serializable) selectedItemList);
                    mIntent.putExtra(ConstantUtil.KEY_2, selectedRegionBean);
                    mIntent.putExtra("EngineeringORderCategory", CommonEnum.EngineeringORderCategory.PUBLICATION);
//                    mIntent.putExtra("regionName", selectedRegionBean.getRegionName());
//
//                    /*用于获取点位信息*/
//                    mIntent.putExtra(ConstantUtil.KEY_2, selectedRegionBean.getId());


                    startActivityForResult(mIntent, ConstantUtil.START_ACTIVITY_KEY_1);
                }


                break;
            case R.id.edt_airport_name:
                currentPop = AIRPORT;
                showAirportPop();
                break;
            case R.id.edt_ndustry_classification:
                currentPop = INDUSTRY;
                showClassificationPop();
                break;
            case R.id.edt_completion_date:
            case R.id.img_completion_date:
                showDateDialog();
                break;

            case R.id.btn_save:
                save();
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case ConstantUtil.START_ACTIVITY_KEY_1:
                if (data != null) {
                    selectedItemList = (List<String>) data.getSerializableExtra(ConstantUtil.KEY_1);
                    datas = (List<MediaBean>) data.getSerializableExtra(ConstantUtil.KEY_2);
                    initData();
                }
                break;
            case PhotoUtil.CAMERA:

                if (resultCode == RESULT_OK) {
                    File picture = new File(PhotoUtil.filePath);
                    if (!picture.exists()) {
                        picture = new File(PhotoUtil.filePath);
                    }

                    filePath = PhotoUtil.CAMERA_SEVER + picture.getName();
                    filePath = PhotoUtil.imageCompressionAndSave(picture.getAbsolutePath(), filePath);
                    //override(100, 100)


                    if (pathList.contains("paizhao")) {
                        pathList.remove("paizhao");
                    }
                    if (pathList.size() < 3) {
                        pathList.add(filePath);
                        if (pathList.size() < 3)
                            pathList.add("paizhao");

                        gridAdapter.setData(pathList);
                        gridAdapter.notifyDataSetChanged();
                    }


                    uploadPhotoPresenter.uploadPhtoto();
                }


                break;
            case PhotoUtil.GALLERY:
                if (resultCode == RESULT_OK) {

                    String path = FileUtil.getRealPathFromURI(this, Uri.parse(data.getData() + ""));

                    if (pathList.contains("paizhao")) {
                        pathList.remove("paizhao");
                    }

                    if (pathList.size() < 3) {

                        pathList.add(path);
                        if (pathList.size() < 3)
                            pathList.add("paizhao");
                        gridAdapter.setData(pathList);
                        gridAdapter.notifyDataSetChanged();
                    }


                    File f = new File(path);
                    filePath = PhotoUtil.CAMERA_SEVER + f.getName();
                    filePath = PhotoUtil.imageCompressionAndSave(path, filePath);
//                    filePath = data.getData() + "";
                    uploadPhotoPresenter.uploadPhtoto();
//                    if (f.exists()) {
//                        f.delete();
//                    }

                }
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (airportPopwindow != null) {
            airportPopwindow.dismiss();
            airportPopwindow = null;
        }

        if (classificationPopwindow != null) {
            classificationPopwindow.dismiss();
            classificationPopwindow = null;
        }
    }

    @Override
    public long getBeginDate() {

        return System.currentTimeMillis();
    }

    @Override
    public long getCompleteDate() {

        return DateUtil.getMillis(edt_completion_date.getText().toString().trim());

    }

    @Override
    public String getIndustryCategory() {
        return edt_ndustry_classification.getText().toString().trim();
    }

    @Override
    public List<MediaBean> getMediaList() {

        return datas;
    }

    @Override
    public List<String> getPicList() {
        return serverUrlList;
    }

    @Override
    public String getPublicationContent() {
        return edt_publication_content.getText().toString().trim();
    }

    @Override
    public String getRegionId() {
        if (null != selectedRegionBean)
            return selectedRegionBean.getId();
        return "";
    }

    @Override
    public String getRegionName() {
        if (null != selectedRegionBean)
            return selectedRegionBean.getRegionName();

        return "";
    }

    @Override
    public void addPublicationOrderSuccessed(String id) {
        Toast.makeText(this, "保存成功" + id, Toast.LENGTH_SHORT).show();
        Intent mIntent = new Intent();
        mIntent.putExtra(ConstantUtil.KEY_1, true);
        setResult(ConstantUtil.CREATED_ORDER, mIntent);
        finish();
    }

    @Override
    public void getMediaRegionListSuccessed(List<RegionBean> regionBeanList) {
        airPopRegionBeanLs = regionBeanList;
        initAirportPopData();
    }

    @Override
    public void showFailedError(String desc) {
        Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
    }

    @Override
    public String getFilePath() {
        return filePath;
    }

    public void upLoadPhotoSuccessed(String uri) {
        serverUrlList.add(uri);
    }

    @Override
    public void upLoadPhotoFailed(String desc) {
        Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }


}
